/*
 * @Author: jianglijun 
 * @Date: 2019-02-23 23:21:55 
 * @Last Modified by: jianglijun
 * @Last Modified time: 2019-02-28 05:33:38
 */
var express = require('express');
var router = express.Router();
var User = require("../models/user")
var utils = require("../comm/utils")
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// --------------  用户登录  ----------------  //
router.post('/login', function(req, res, next) {
  if(!req.session.user&& !req.cookies.userId){
    
  }else{
    let userId = req.cookies.userId;
    User.findOne({userId},(err,data01) => {
      if(err){
        res.json({
          errno:1001,
          msg:err.message
        })
      }
      else{
        if(!data01){
          res.json({
            errno:1,
            msg:"没有用户"
          })
        }
        else{
          res.json({
            errno:1002,
            msg:"已经登录",
            data:{
              userId,
              nickname:data01.userName
            }
          })
          
        }
      }

    })

    return;
   
  }
  
   let param = {
      userName:req.body.userName,
      userPassword:req.body.userPassword.toString()
     
   }
   true;
   User.findOne(param,(err,data) =>{
     if(err){
        res.json({
          errno:1001,
          msg:err.message
        })
     }
     else {
       if(!data){
        res.json({
          errno:1,
          msg:"密码不正确"
        })
       }else{
        res.cookie('userId', data.userId, { maxAge: 1000*60*60*24, path: "/" });
        req.session.user = data;
        res.json({
          errno:0,
          msg:"密码正确",
          data:{
            "userId":data.userId,
            "userName":data.userName
          }

        })
       }
     }
   })
});
// -------------  检测是否存在此用户名  --------  //
router.get("/user",(req, res, next) => {
  let param = {
    userName:req.param("userName")
  }
  User.findOne(param,(err,doc) => {
    
    if(err){
      res.json({
        errno:1001,
        msg:err.message
      })
    }
    else {
      if(!doc){
        res.json({
          errno:1,
          msg:"该用户不存在"
        })
      }
      else{
        res.json({
          errno:0,
          msg:"该用户存在"
        })
      }
    }
  })
})
//  -------------  检测是否在登录状态 ------- //
router.get("/islogin",(req,res,next) => {
  if(!req.session.user&& !req.cookies.userId){
    
  }else{
    let userId = req.cookies.userId;
    User.findOne({userId},(err,data01) => {
      if(err){
        res.json({
          errno:1001,
          msg:err.message
        })
      }
      else{
        if(!data01){
          res.json({
            errno:1,
            msg:"没有用户"
          })
        }
        else{
          res.json({
            errno:0,
            msg:"已经登录",
            data:{
              userId,
              nickname:data01.userName
            }
          })
          
        }
      }

    })
    return;
  }
})
//  -------------  退出登录  ---------  //
router.get("/logout",(req,res,next) => {
  res.clearCookie('userId', { path: '/', maxAge:1000*60*60*24});
  req.session.destroy(function(err) {
    if(err){
      res.json({errno: 2, msg:err.message});
      return;
    }
    res.clearCookie('userId', { path: '/', maxAge:1000*60*60*24});
    res.json({
      errno:0,
      msg:"退出登录",
      data:"退出登录"
    })
  });
})
// ------------------- 购物车列表  --------- //
router.get("/cartlist",(req,res) => {
  let userId = req.cookies.userId;
  let checked = req.param("checked") || 'all';
  User.findOne({userId},(err,doc) => {
    if(err){
      res.json({
        errno:1001,
        msg:err.message
      })
    }else{
      if(!doc){
        res.json({
          errno:1,
          msg:"没有用户"
        })
      }
      else{
        let newArray = [];
        if(checked == 'checked'){
          newArray = doc.cartList.filter( item => item.checked ==true );
        }else{
          newArray = doc.cartList;
        }
        
        res.json({
          errno:0,
          msg:"成功",
          data:newArray
        })
      }
    }
  })
})
//  ------------- 删除购物车指定的商品 --------//
router.get("/cartDel",(req,res,next) => {
  let userId = +req.cookies.userId;
  let productId = +req.param("productId");
  User.update(
    {userId},
    {
      $pull:{
        "cartList":{
          productId
        }
      }
    },(err,doc) => {
      if(err){
        res.json({errno: 1, msg:err.message});
        return;
      }
      else{
        let {nModified,ok} = doc;
        if(nModified==1&&ok==1){
          res.json({
            erron:0,
            msg:"删除成功",
            data:"删除成功"
          })
        }else{
          res.json({
            erron:0,
            msg:doc,
            data:""
          })
        }
      }
    }
  )
})
// -------------- 编辑购物车  ----------//
router.get("/editCart",(req,res,next) => {
  let userId = +req.cookies.userId;
  let productId = req.param("productId");
  let productNum = +req.param("productNum");
  let checked = req.param("checked");
  User.update(
    {userId,
      "cartList.productId":productId
    },
    {
      "cartList.$.productNum":productNum,
      "cartList.$.checked":checked
    },
    (err,doc) =>{
      if(err){
        res.json({errno: 1, msg:err.message});
        return;
      }else{
        let {nModified,ok} = doc;
        if(nModified==1 && ok ==1){
            res.json({
            erron:0,
            msg:"删除成功",
            data:"成功"
          })
        }
        else {
            res.json({
              erron:101,
              msg:"数据没有存在，不能被删除",
              data:""
            })
        }
      }
    }
  )

})
// ------------- 编辑 All 状态 ------------ //
router.get("/allChecked",(req,res,next) => {
  let userId = +req.cookies.userId;
  let checked = req.param("checked");
  User.findOne({userId},(err,doc) => {
    if(err){
      res.json({errno: 1, msg:err.message});
    }else{
      if(!doc){
        res.json({errno: 1, msg:doc});
      }
      else{
        doc.cartList.forEach(ele => {
          ele.checked = checked;
        });
        doc.save((err1,doc1) => {
          if(err){
            res.json({errno: 1, msg:err1.message});
          }else {
            let {nModified,ok} = doc1;
            if(nModified==1 && ok ==1){
              res.json({errno: 0, msg:"成功",data:"成功"});                          
            }else{
              res.json({
                erron:101,
                msg:"数据没有存在，不能被删除",
                data:""
              })
            }         
          }
        })
      }
    }
  })
}) 
// ------------ 支付生成订单号 -----------
router.post("/buildCode",(req,res,next) => {
  let userId = +req.cookies.userId,
    addressId = req.body.addressId;
  let a = 0.8;
  let b = 45;
  User.findOne({userId},(err,doc) => {
    if(err){
      res.json({
        errno:1,
        msg:err.message
      })
    } 
    else {
      if(doc){
        let addressInfo = doc.addressList.find(item => item.addressId == addressId); // 地址
        let goodsList = doc.cartList.filter(item1 => item1.checked==true);
        let orderTotal = 0;
        goodsList.forEach(item => {
          orderTotal += item.salePrice*item.productNum
        })
        orderTotal = (parseInt(orderTotal))*8/10-45;

        let sysDate = utils.formatDate(new Date(),"yyyyMMddhhmmss");
        var platform = '622';
        var r1 = Math.floor(Math.random()*10);
        var r2 = Math.floor(Math.random()*10);
        var orderId = platform+r1+sysDate+r2;
        let orderList = {
          "orderId":orderId,
          "orderTotal":orderTotal,
          "addressInfo":addressInfo,
          "goodsList":goodsList,
          "orderStatus":1,
          "createDate":new Date()
        }
        doc.orderList.push(orderList);
        doc.cartList = [];
        doc.save((err1,doc11) => {
          if(err1){
            res.json({
              error:1,
              msg:err1.message
            })
          }else{
            res.json({
              error:0,
              msg:"成功",
              data:{orderId}
            })
          }
        })
      }
    }
  })
})
// ---------- 根据订单号获取详情
router.get("/orderDetail",(req,res,next) => {
  let userId = +req.cookies.userId,
      orderId = req.param("orderId");
  User.findOne({userId},(err,doc) => {
    if(err){
      res.json({
        errno:1,
        msg:err.message
      })
    } 
    else {
      if(doc){
        let orderDetail = doc.orderList.find(item => item.orderId == orderId);
        if(orderDetail){
          res.json({
            errno:0,
            msg:"成功",
            data:{
              orderId:orderDetail.orderId,
              orderTotal:orderDetail.orderTotal,
              createDate:Date.parse(orderDetail.createDate),
              addressInfo:orderDetail.addressInfo,
              goodsList:orderDetail.goodsList
            }
          })
        }else{
          res.json({
            errno:1202,
            msg:"无此订单"
          })
        }
      }
    }
  })
})
module.exports = router;
